import Https from "@/utils/Https";
import { CloseCircleFilled, ReloadOutlined } from "@ant-design/icons";
import {
  Button,
  ColorPicker,
  Descriptions,
  Drawer,
  Form,
  InputNumber,
  message,
  Rate,
  Space,
  TimePicker,
  Spin,
  Modal,
  Select,
} from "antd";
import dayjs from "dayjs";
import { FC, useEffect, useState } from "react";
import { courseDuration, disableWorkTime, weekNameList } from "../../interface";
import styles from "../styles.less";
const EditWork: FC<any> = (props) => {
  const { open, venueHours, onSuccess, onClose, info, workDate } = props;
  const [courseInfo, setCourseInfo] = useState<any>({});
  const [form] = Form.useForm();
  const [isEdit, setIsEdit] = useState(false);
  const [loading, setLoading] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [courseList, setCourseList] = useState([]);
  const [courseLoading, setCourseLoading] = useState(false);
  const [roomList, setRoomList] = useState([]);
  const [roomLoading, setRoomLoading] = useState(false);
  //禁用时间区间
  const { disabledHours, disabledMinutes } = disableWorkTime(
    dayjs(venueHours.venueStart, "HH:mm"),
    dayjs(venueHours.venueEnd, "HH:mm"),
    15
  );
  //获取排课信息详情
  const getDetails = async (id) => {
    setLoading(true);
    let res = await Https.get(`/course/sched/scheduleDetail/${id}`, {}, true);
    setLoading(false);
    if (res.code == 200 && res.data) {
      setCourseInfo(res.data);
    } else {
      message.error(res.msg);
    }
  };
  //保存排课信息
  const save = async () => {
    let res = await form.validateFields();
    let params = {
      id: courseInfo.id,
      venueId: courseInfo.venueId,
      courseType: courseInfo.courseType,
      courseId: courseInfo.courseId,
      courseCoachId: res.courseCoachId,
      courseDuration: res.courseDuration,
      peopleNumMax: res.peopleNumMax,
      courseDifficulty: res.courseDifficulty,
      colour: res.colour,
      classRoom: res.classRoom,
      startTimeSlot:
        workDate + " " + dayjs(res.startTimeSlot).format("HH:mm:ss"),
      endTimeSlot: workDate + " " + dayjs(res.endTimeSlot).format("HH:mm:ss"),
    };
    setLoading(true);
    let result = await Https.post("/course/sched/updateSchedule", params, true);
    if (result.code == 200) {
      message.success("保存成功");
      onSuccess();
    } else {
      message.error(result.msg);
    }
    setLoading(false);
  };
  //删除排课
  const deleteWork = async () => {
    setLoading(true);
    let res = await Https.post(
      `/course/sched/logicDeleteSchedule/${courseInfo.id}`,
      {},
      true
    );
    setLoading(false);
    if (res.code == 200) {
      message.success("删除成功");
      setModalOpen(false);
      onSuccess();
    } else {
      setModalOpen(false);
      Modal.error({
        title: (
          <span>
            <CloseCircleFilled
              style={{ color: "red", fontSize: "20px", marginRight: "10px" }}
            />
            删除失败提示
          </span>
        ),
        icon: null,
        content: res.msg,
      });
    }
  };
  //获取老师列表
  const getCourseList = async (startTime, endTime) => {
    setCourseLoading(true);
    let res = await Https.get(
      "/employee/manage/queryCoachByVenueId",
      {
        venueId: courseInfo.venueId,
        scheduleId: courseInfo.id,
        startTime,
        endTime,
      },
      true
    );
    setCourseLoading(false);
    if (res.code == 200) {
      setCourseList(res.data);
    } else {
      setCourseList([]);
    }
  };
  //获取教室列表
  const getRoomList = async () => {
    setRoomLoading(true);
    let res = await Https.get(
      "/course/sched/classRoomAllList",
      { venueId: courseInfo.venueId },
      true
    );
    setRoomLoading(false);
    if (res.code == 200) {
      setRoomList(res.data);
    } else {
      setCourseList([]);
    }
  };
  useEffect(() => {
    if (open) {
      setIsEdit(false);
      form.resetFields();
      setCourseInfo({});
      setRoomList([]);
      setCourseList([]);
      getDetails(info.id);
    }
  }, [open, info]);
  return (
    <Drawer
      title={
        <span>
          排课信息({workDate} 周
          {weekNameList[dayjs(workDate).day() == 0 ? 7 : dayjs(workDate).day()]}
          ){info.isExpired == 1 && "-已过期"}
        </span>
      }
      onClose={() => {
        onClose();
      }}
      destroyOnClose={true}
      maskClosable={true}
      width="60%"
      rootClassName={styles.editWorkClass}
      open={open}
      footer={
        info.isExpired == 0 && (
          <Space>
            <Button
              size="large"
              danger
              loading={loading}
              onClick={() => {
                setModalOpen(true);
              }}
            >
              删除
            </Button>
            {!isEdit ? (
              <Button
                onClick={() => {
                  setIsEdit(true);
                  if (courseList.length == 0) {
                    getCourseList(
                      courseInfo.startTimeSlot,
                      courseInfo.endTimeSlot
                    );
                  }
                  if (roomList.length == 0) {
                    getRoomList();
                  }
                  form.setFieldsValue({
                    ...courseInfo,
                    startTimeSlot: dayjs(courseInfo.startTimeSlot),
                    endTimeSlot: dayjs(courseInfo.endTimeSlot),
                  });
                }}
                size="large"
                type="primary"
              >
                编辑
              </Button>
            ) : (
              <>
                <Button
                  onClick={() => {
                    setIsEdit(false);
                    form.resetFields();
                  }}
                  type="default"
                  size="large"
                >
                  取消
                </Button>
                <Button
                  onClick={() => {
                    save();
                  }}
                  loading={loading}
                  size="large"
                  type="primary"
                >
                  保存
                </Button>
              </>
            )}
          </Space>
        )
      }
    >
      <Spin spinning={loading}>
        <Form form={form}>
          <Descriptions column={2} title="课程信息" layout="vertical" bordered>
            <Descriptions.Item label="课程名称">
              {courseInfo.courseName}
            </Descriptions.Item>
            <Descriptions.Item label="授课老师">
              {!isEdit ? (
                courseInfo.courseCoachName
              ) : (
                <>
                  <Form.Item
                    label=""
                    name="courseCoachId"
                    rules={[{ required: true, message: "请选择授课老师" }]}
                    style={{
                      display: "inline-block",
                      width: "80%",
                    }}
                  >
                    <Select
                      placeholder="请选择授课老师"
                      getPopupContainer={(triggerNode) =>
                        triggerNode.parentElement
                      }
                      loading={courseLoading}
                    >
                      {courseList &&
                        courseList.map((item) => (
                          <Select.Option
                            disabled={item.status == 1}
                            key={item.userId}
                            value={item.userId}
                          >
                            {item.nickName}
                          </Select.Option>
                        ))}
                    </Select>
                  </Form.Item>
                  <ReloadOutlined
                    title="刷新"
                    onClick={() => {
                      let startTime = form.getFieldValue("startTimeSlot")
                        ? dayjs(form.getFieldValue("startTimeSlot")).format(
                            "YYYY-MM-DD HH:mm:ss"
                          )
                        : "";
                      let endTime = form.getFieldValue("endTimeSlot")
                        ? dayjs(form.getFieldValue("endTimeSlot")).format(
                            "YYYY-MM-DD HH:mm:ss"
                          )
                        : "";
                      getCourseList(startTime, endTime);
                    }}
                    style={{
                      color: "#1677ff",
                      marginLeft: "10px",
                      marginTop: "8px",
                    }}
                  />
                </>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="单节课时长(分钟)">
              {!isEdit ? (
                courseInfo.courseDuration
              ) : (
                <Form.Item
                  label=""
                  name="courseDuration"
                  rules={[{ required: true, message: "请选择单节课时长。" }]}
                >
                  <Select
                    placeholder="请选择单节课时长"
                    getPopupContainer={(triggerNode) =>
                      triggerNode.parentElement
                    }
                    onChange={() => {
                      form.setFieldsValue({
                        startTimeSlot: null,
                        endTimeSlot: null,
                      });
                    }}
                  >
                    {courseDuration &&
                      courseDuration.map((item) => (
                        <Select.Option key={item.value} value={item.value}>
                          {item.label}
                        </Select.Option>
                      ))}
                  </Select>
                </Form.Item>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="可约人数">
              {!isEdit ? (
                courseInfo.peopleNumMax
              ) : (
                <Form.Item
                  label=""
                  name="peopleNumMax"
                  rules={[{ required: true, message: "请输入可预约人数" }]}
                >
                  <InputNumber
                    style={{ width: "100%" }}
                    min={1}
                    max={1000}
                    precision={0}
                    controls={false}
                    suffix="人"
                    placeholder="请输入可预约人数"
                  />
                </Form.Item>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="课程难度">
              {!isEdit ? (
                <Rate
                  value={courseInfo.courseDifficulty}
                  disabled={!isEdit}
                ></Rate>
              ) : (
                <Form.Item label="" name="courseDifficulty">
                  <Rate />
                </Form.Item>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="排课颜色">
              {!isEdit ? (
                <div
                  style={{
                    background: courseInfo.colour,
                    width: "100%",
                    height: "30px",
                    borderRadius: "4px",
                  }}
                ></div>
              ) : (
                <Form.Item
                  label=""
                  name="colour"
                  rules={[{ required: true, message: "请选择颜色" }]}
                >
                  <ColorPicker
                    showText
                    disabledAlpha
                    onChange={(e) => {
                      form.setFieldsValue({ colour: e.toHexString() });
                    }}
                  />
                </Form.Item>
              )}
            </Descriptions.Item>
          </Descriptions>
          <Descriptions
            style={{ marginTop: "20px" }}
            title="排课信息"
            layout="vertical"
            bordered
          >
            <Descriptions.Item label="上课教室">
              {!isEdit ? (
                courseInfo.classRoomName
              ) : (
                <>
                  <Form.Item
                    label=""
                    name="classRoom"
                    rules={[{ required: true, message: "请选择上课教室" }]}
                    style={{
                      display: "inline-block",
                      width: "80%",
                    }}
                  >
                    <Select
                      placeholder="请选择上课教室"
                      getPopupContainer={(triggerNode) =>
                        triggerNode.parentElement
                      }
                      loading={roomLoading}
                    >
                      {roomList &&
                        roomList.map((item) => (
                          <Select.Option
                            disabled={item.roomStatus == 1}
                            key={item.id}
                            value={item.id}
                          >
                            {item.classRoomName}
                          </Select.Option>
                        ))}
                    </Select>
                  </Form.Item>
                  <ReloadOutlined
                    title="刷新"
                    onClick={() => {
                      getRoomList();
                    }}
                    style={{
                      color: "#1677ff",
                      marginLeft: "10px",
                      marginTop: "8px",
                    }}
                  />
                </>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="开始-结束时间">
              {!isEdit ? (
                <span>
                  {dayjs(courseInfo.startTimeSlot).format("HH:mm")} ~
                  {dayjs(courseInfo.endTimeSlot).format("HH:mm")}
                </span>
              ) : (
                <div style={{ display: "flex" }}>
                  <Form.Item
                    label=""
                    name="startTimeSlot"
                    rules={[{ required: true, message: "请选择开始时间" }]}
                  >
                    <TimePicker
                      format={"HH:mm"}
                      minuteStep={15}
                      disabledHours={disabledHours}
                      disabledMinutes={disabledMinutes}
                      allowClear={false}
                      getPopupContainer={(triggerNode) =>
                        triggerNode.parentElement
                      }
                      onChange={(e) => {
                        let interval = form.getFieldValue("courseDuration");
                        let nowStartTime =
                          workDate + " " + dayjs(e).format("HH:mm:ss");
                        let endTime = dayjs(nowStartTime).add(
                          interval,
                          "minute"
                        );
                        let nowEndTime = dayjs(endTime).format(
                          "YYYY-MM-DD HH:mm:ss"
                        );
                        if (
                          dayjs(nowStartTime) < dayjs() ||
                          dayjs(nowEndTime) < dayjs()
                        ) {
                          message.error("排课时间已过期，不能进行排课!");
                          form.setFieldsValue({
                            startTimeSlot: "",
                            endTimeSlot: "",
                          });
                          return;
                        }
                        let venueEnd =
                          workDate + " " + venueHours.venueEnd + ":00";
                        if (nowEndTime <= venueEnd) {
                          form.setFieldsValue({
                            endTimeSlot: dayjs(endTime),
                          });
                        } else {
                          message.error("结束时间超出场馆运营时间范围!");
                          form.setFieldsValue({
                            startTimeSlot: "",
                            endTimeSlot: "",
                          });
                        }
                      }}
                    />
                  </Form.Item>
                  <Form.Item
                    label=""
                    name="endTimeSlot"
                    style={{ marginLeft: "15px" }}
                  >
                    <TimePicker format={"HH:mm"} placeholder="" disabled />
                  </Form.Item>
                </div>
              )}
            </Descriptions.Item>
          </Descriptions>
        </Form>
      </Spin>
      <Modal
        onCancel={() => {
          setModalOpen(false);
        }}
        onOk={() => {
          deleteWork();
        }}
        confirmLoading={loading}
        open={modalOpen}
        title={
          <span>
            <CloseCircleFilled
              style={{ color: "red", fontSize: "20px", marginRight: "10px" }}
            />
            提示
          </span>
        }
      >
        是否删除这条排课信息？
      </Modal>
    </Drawer>
  );
};
export default EditWork;
